<?php

namespace App\Http\Controllers\API;

use App\Http\Controllers\Controller;
use App\Http\Requests\CompanyRequest;
use App\Models\Company;
use App\Models\User;
use Illuminate\Http\Request;
use App\Models\District;
use App\Models\School;
use App\Models\SchoolDept;
use App\Models\SchoolSpeciality;
use Illuminate\Support\Facades\DB;

class CompanyController extends Controller
{
    /**
     * @param Request $request
     * @return mixed
     */
    public function index(Request $request)
    {
        $name = trim($request->get('name', ''));
        $mobile = trim($request->get('mobile', ''));
        $provinceId = intval($request->get('province_id', 0));          //省
        $cityId = intval($request->get('city_id', 0));                  //市
        $status = intval($request->get('is_complete', -1));
        $workCompany = trim($request->get('work_company', ''));

        $query = Company::withTrashed();
        $query->when($name, function ($queryString) use ($name) {
            return $queryString->where('name', 'like', '%' . $name . '%');
        })->when($mobile, function ($queryString) use ($mobile) {
            return $queryString->where('mobile', $mobile);
        })->when($provinceId, function ($queryString) use ($provinceId) {
            return $queryString->where('province_id', $provinceId);
        })->when($cityId, function ($queryString) use ($cityId) {
            return $queryString->where('city_id', $cityId);
        })->when($workCompany, function ($queryString) use ($workCompany) {
            return $queryString->where('work_company', 'like', '%' . $workCompany . '%');
        });

        if($status > -1){
            if ($status == 0){
                $query->where('is_complete', 0);
            }elseif ($status == 1){
                $query->where('is_complete', 1);
            }
        }
        $models = $query->orderByDesc('id')->paginate();
        return $models;
    }

    /**
     * @param CompanyRequest $request
     * @return CompanyPersonage|\Illuminate\Contracts\Routing\ResponseFactory|\Symfony\Component\HttpFoundation\Response
     */
    public function store(CompanyRequest $request)
    {
        $data = $request->all();
        $userInfo = User::where('mobile', $data['mobile'])->first();
        if ($userInfo) {
            return response(['is_unique' => '该手机号已经注册'], 422);
        }
        $gender = $data['gender'];
        $dob = $data['dob'];
        if ($data['certificates_type'] == 1) {          //身份证
            if (preg_match('/^(([0-9]{18})|([0-9]{17}x)|([0-9]{17}X))$/', $data['id_card'])) {
                $teacherInfo = str_split($data['id_card'], 1);
                $gender = $teacherInfo[16] % 2 == 1 ? '男' : '女';
                $dob = substr($data['id_card'], 6, 8);
            } else {
                return response(['id_card' => '证件号码有误'], 422);
            }
        } elseif ($data['certificates_type'] == 3) {    //护照
            if (preg_match('/^((H[0-9]{11})|(M[0-9]{11}))$/', $data['id_card']) == 0) {
                return response(['id_card' => '证件号码有误'], 422);
            }
        }else{
            //
        }
        $user = new User();
        $user->mobile = $data['mobile'];
        $user->password = bcrypt($data['mobile']);
        $user->type = User::TYPE_COMPANY;
        $user->confirmed = 0;
        $user->uc_status = false;
        if ($user->save()){
            $model = new Company();
            $model->fill($data);
            $model->gender = $gender;
            $model->dob = $dob;
            $model->is_complete = 0;
            $model->user_id = $user->id;
            $model->sign_pic = 'backend/add';
            $model->province_cn = District::find($data['province_id'])->name;
            $model->city_cn = District::find($data['city_id'])->name;
            if ($data['finish_province_id']){
                $model->finish_province_cn = District::find($data['finish_province_id'])->name;
            }
            if ($data['finish_city_id']){
                $model->finish_city_cn = District::find($data['finish_city_id'])->name;
            }
            if ($data['finish_school_id']){
                $model->finish_school_cn = School::find($data['finish_school_id'])->name;
            }
            if ($data['finish_dept_id']){
                $model->finish_dept_cn = SchoolDept::find($data['finish_dept_id'])->name;
            }
            if ($data['finish_speciality_id']){
                $model->finish_speciality_cn = SchoolSpeciality::find($data['finish_speciality_id'])->name;
            }
            if ($model->save()) {
                return $model;
            }else{
                return response($model->getErrors()->toArray(), 406);
            }
        }else{
            return response(['save_status' => 'user save fail'], 406);
        }
    }

    /**
     * @param CompanyRequest $request
     * @param $id
     * @return \Illuminate\Contracts\Routing\ResponseFactory|mixed|\Symfony\Component\HttpFoundation\Response
     */
    public function update(CompanyRequest $request, $id)
    {
        $data = $request->all();
        $model = $this->findModel($id);
        $userInfo = User::where('mobile', $data['mobile'])->where('id', '!=', $model->user_id)->first();
        if ($userInfo) {
            return response(['is_unique' => '该手机号已经注册'], 422);
        }
        $gender = $data['gender'];
        $dob = $data['dob'];
        if ($data['certificates_type'] == 1) {          //身份证
            if (preg_match('/^(([0-9]{18})|([0-9]{17}x)|([0-9]{17}X))$/', $data['id_card'])) {
                $teacherInfo = str_split($data['id_card'], 1);
                $gender = $teacherInfo[16] % 2 == 1 ? '男' : '女';
                $dob = substr($data['id_card'], 6, 8);
            } else {
                return response(['id_card' => '证件号码有误'], 422);
            }
        } elseif ($data['certificates_type'] == 3) {    //护照
            if (preg_match('/^((H[0-9]{11})|(M[0-9]{11}))$/', $data['id_card']) == 0) {
                return response(['id_card' => '证件号码有误'], 422);
            }
        }else{
            //
        }
        $model->fill($data);
        $model->gender = $gender;
        $model->dob = $dob;
        $model->province_cn = District::find($data['province_id'])->name;
        $model->city_cn = District::find($data['city_id'])->name;
        if ($data['finish_province_id']){
            $model->finish_province_cn = District::find($data['finish_province_id'])->name;
        }else{
            $model->finish_province_cn = null;
        }
        if ($data['finish_city_id']){
            $model->finish_city_cn = District::find($data['finish_city_id'])->name;
        }else{
            $model->finish_city_cn = null;
        }
        if ($data['finish_school_id']){
            $model->finish_school_cn = School::find($data['finish_school_id'])->name;
        }else{
            $model->finish_school_cn = null;
        }
        if ($data['finish_dept_id']){
            $model->finish_dept_cn = SchoolDept::find($data['finish_dept_id'])->name;
        }else{
            $model->finish_dept_cn = null;
        }
        if ($data['finish_speciality_id']){
            $model->finish_speciality_cn = SchoolSpeciality::find($data['finish_speciality_id'])->name;
        }else{
            $model->finish_speciality_cn = null;
        }
        $companyUser = User::findOrFail($model->user_id);
        $companyUser->mobile = $data['mobile'];
        if ($model->save()) {
            $companyUser->save();
            return $model;
        }else{
            return response($model->getErrors()->toArray(), 406);
        }
    }

    /**
     * 禁用社会人士
     * @param $id
     * @return array
     */
    public function destroy($id)
    {
        $model = $this->findModel($id);
        try {
            $model->delete();
            return response(['禁用成功！'], 200);
        } catch (\Exception $e) {
            return response(['禁用失败！'], 406);
        }
    }

    /**
     * @param $id
     * @return mixed
     */
    public function show($id)
    {
        $model = $this->findModel($id);
        return $model;
    }

    /**
     * 永久删除社会人士
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getForceDelete($id)
    {
        $model = $this->findModel($id);
        try {
            $teacher = User::find($model->user_id);
            $teacher->forceDelete();
            $model->forceDelete();
            DB::table('works_author')->where('author_id', $model->user_id)->delete();
            DB::table('xyj_teams')->where('team_member_id', $model->user_id)->delete();
            return response(['删除成功'], 200);
        } catch (\Exception $e) {
            return response(['删除失败'], 406);
        }
    }

    /**
     * 启用社会人士
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getInvocation($id)
    {
        try {
            DB::table('xyj_company_personage')->where('id', $id)->update(['deleted_at' => null]);
            return response(['启用成功'], 200);
        } catch (\Exception $e) {
            return response(['启用失败'], 406);
        }
    }


    /**
     * 解绑社会人士微信
     * @param $id
     * @return \Illuminate\Http\RedirectResponse
     */
    public function getOpenIdDelete($id)
    {
        $model = $this->findModel($id);
        try {
            $model->user->open_id = null;
            $model->user->save();
            $model->is_complete = 0;
            $model->save();
            return response(['解绑成功'], 200);
        } catch (\Exception $e) {
            return response(['解绑失败'], 406);
        }
    }

    /**
     * @param $id
     * @return mixed
     */
    public function findModel($id)
    {
        $model = Company::withTrashed()->where('id', $id)->first();
        return $model;
    }


}